<template>
    <div class="container">
        <div class="page-container">
            <div class="forgot-password">
                <el-button v-show="active >= '1'" class="return-page-wr" type="primary" text icon="ArrowLeft"
                    @click="beforeSteps">上一步</el-button>
                <el-button v-show="active == '0'" class="return-page-wr" type="primary" text icon="ArrowLeft"
                    @click="$router.push({ path: '/login' })">返回</el-button>
                <div class="content">
                    <el-steps :active="active" finish-status="success" align-center>
                        <el-step title="用户"></el-step>
                        <el-step title="重置密码"></el-step>
                        <el-step title="验证码"></el-step>
                        <el-step title="完成设置"></el-step>
                    </el-steps>
                    <div v-if="active == '0'">
                        <div class="form-container">
                            <el-form ref="forgetFormRef1" :model="data.form" status-icon :rules="data.form_rules"
                                label-width="100px" class="demo-ruleForm">
                                <el-form-item label="用户名：" prop="account">
                                    <el-input v-model="data.form.account" prefix-icon="User"
                                        placeholder="请输入用户名"></el-input>
                                </el-form-item>
                                <el-form-item label="邮箱：" prop="email">
                                    <el-input v-model="data.form.email" prefix-icon="Message"
                                        placeholder="请输入邮箱"></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-button type="primary" style="margin-top: 12px;float:right;"
                            @click="isUserExistbutton">下一步<el-icon class="el-icon--right">
                                <ArrowRight />
                            </el-icon></el-button>
                    </div>
                    <div v-if="active == '1'">
                        <div class="form-container">
                            <el-form ref="forgetFormRef2" :model="data.form" status-icon :rules="data.form_rules"
                                label-width="100px" class="demo-ruleForm">
                                <el-form-item label="新密码：" prop="password">
                                    <el-input type="password" v-model="data.form.password" prefix-icon="Lock"
                                        placeholder="请输入新密码" show-password></el-input>
                                </el-form-item>
                                <el-form-item label="确认密码：" prop="passwords">
                                    <el-input type="password" v-model="data.form.passwords" prefix-icon="Lock"
                                        placeholder="请确认密码" show-password></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-button type="primary" style="margin-top: 12px;float:right;"
                            @click="passwordValidate">下一步<el-icon class="el-icon--right">
                                <ArrowRight />
                            </el-icon></el-button>
                    </div>
                    <div v-if="active == '2'">
                        <div class="form-container">
                            <el-form ref="forgetFormRef3" :model="data.form" status-icon :rules="data.form_rules"
                                label-width="100px" class="demo-ruleForm">
                                <el-form-item prop="code" label="验证码：" style="margin-top: 20px;">
                                    <el-row :gutter="10">
                                        <el-col :span="14">
                                            <el-input v-model="data.form.code"></el-input>
                                        </el-col>
                                        <el-col :span="10">
                                            <el-button type="success" class="el-button-block"
                                                :loading="data.code_button_loading" :disabled="data.code_button_disabled"
                                                @click="handlerGetCode">
                                                {{ data.code_button_text }}
                                            </el-button>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-button type="primary" style="margin-top: 12px;float:right;" 
                        :disabled="data.submit_button_disabled" @click="resetPassword">确定<el-icon
                                class="el-icon--right">
                                <ArrowRight />
                            </el-icon></el-button>
                    </div>
                    <div v-if="active == '3'">
                        <div class="reset-success">
                            <el-icon :size="100" style="margin-right:10px;color:green;">
                                <SuccessFilled />
                            </el-icon>
                            <p class="set-success">设置成功，去登录</p>
                        </div>
                        <div class="btn-wr">
                            <el-button type="success" class="login-btn" @click="$router.push({ path: '/login' })">登录
                                <el-icon class="el-icon--right">
                                    <ArrowRight />
                                </el-icon></el-button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { computed, getCurrentInstance, reactive, ref, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ForgetPassword, GetForCode, isUserExist } from "../../api/http.js"
// 校验类
import { validate_email, validate_password, validate_code } from "../../utils/validate";
export default {
    name: "forgetPassword",
    setup() {
        const active = ref(0)
        const { proxy } = getCurrentInstance()
        const router = useRouter()
        const { go } = useRouter();
        // 用户名校验
        const validate_account_rules = (rule, value, callback) => {
            // let regEmail = validate_name(value);
            if (value === '') {
                callback(new Error("请输入用户名"));
            } else {
                callback();
            }
        }
        // 邮箱校验
        const validate_email_rules = (rule, value, callback) => {
            let regEmail = validate_email(value);
            if (value === '') {
                callback(new Error("请输入邮箱"));
            } else if (!regEmail) {
                callback(new Error("邮箱格式不正确"));
            } else {
                callback();
            }
        }
        //校验密码
        const validate_password_rules = (rule, value, callback) => {
            let regPassword = validate_password(value);
            if (value === '') {
                callback(new Error("请输入密码"));
            } else if (!regPassword) {
                callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
            } else {
                callback();
            }
        }
        // 校验确认密码
        const validate_passwords_rules = (rule, value, callback) => {
            let regPassword = validate_password(value);
            // 获取“密码”
            const passwordValue = data.form.password;
            if (value === '') {
                callback(new Error("请再次输入密码"));
            } else if (!regPassword) {
                callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
            } else if (passwordValue && passwordValue !== value) {
                callback(new Error("两次密码不一致"));
            } else {
                callback();
            }
        }
        const validate_code_rules = (rule, value, callback) => {
            let regCode = validate_code(value);
            if (value === '') {
                callback(new Error("请输入验证码"));
            } else if (!regCode) {
                callback(new Error("请输入6位的验证码"));
            } else {
                callback();
            }
        }
        const data = reactive({
            form: {
                account: "",      // 用户名
                email: "",          //邮箱
                password: "",      // 新密码
                passwords: "",     // 确认密码
                code: "",          // 验证码
            },
            form_rules: {
                account: [
                    { validator: validate_account_rules, trigger: 'change', required: true, }
                ],
                email: [
                    { validator: validate_email_rules, trigger: 'change', required: true, }
                ],
                password: [
                    { validator: validate_password_rules, trigger: 'change', required: true, }
                ],
                passwords: [
                    { validator: validate_passwords_rules, trigger: 'change', required: true, }
                ],
                code: [
                    { validator: validate_code_rules, trigger: 'change', required: true, }
                ]
            },
            /**
             * 获取验证码按钮交互
             */
            code_button_disabled: false,
            code_button_loading: false,
            code_button_text: "获取验证码",
            code_button_timer: null,
            // 提交按钮
            submit_button_disabled: true,
            loading: false
        })
        // 获取验证码
        const handlerGetCode = () => {
            const requestData = {
                //account: data.form.account,
                email: data.form.email,
            }
            data.code_button_loading = true;
            data.code_button_text = "发送中";
            GetForCode(requestData).then(response => {
                const resData = response.data;
                // 激活提交按钮
                data.submit_button_disabled = false;
                proxy.$message({
                    message: resData.message,
                    type: "success"
                })
                // 执行倒计时
                countdown();
            }).catch(error => {
                data.code_button_loading = false;
                data.code_button_text = "获取验证码";
            })
        }

        /** 倒计时 */
        const countdown = (time) => {
            if (time && typeof time !== 'number') { return false; }
            let second = time || 30;                     // 默认时间
            data.code_button_loading = false;              // 取消加载
            data.code_button_disabled = true;              // 禁用按钮
            data.code_button_text = `倒计时${second}秒`;    // 按钮文本
            // 判断是否存在定时器，存在则先清除   
            if (data.code_button_timer) { clearInterval(data.code_button_timer) };
            // 开启定时器  
            data.code_button_timer = setInterval(() => {
                second--;
                data.code_button_text = `倒计时${second}秒`;  // 按钮文本
                if (second <= 0) {
                    data.code_button_text = `重新获取`;         // 按钮文本
                    data.code_button_disabled = false;         // 启用按钮
                    clearInterval(data.code_button_timer);     // 清除倒计时
                }
            }, 1000)
        }
        // 重置
        const resetForm = () => {
            //registerRef.value = { ...data }
            proxy.$refs.forgetFormRef3.resetFields();// 清除定时器
            data.code_button_timer && clearInterval(data.code_button_timer);
            // 获取验证码重置文本
            data.code_button_text = "获取验证码";
            // 获取验证码激活
            data.code_button_disabled = false;
            // 禁用提交按钮
            data.submit_button_disabled = true;
            // 取消提交按钮加载
            data.submit_button_loading = false;
        }
        // 组件销毁之前 - 生命周期
        onBeforeUnmount(() => {
            clearInterval(data.code_button_timer);     // 清除倒计时
        })
        /** 上一步 */
        const beforeSteps = () => {
            if (active.value-- < 0) active.value = 0
        }

        /** 1.第一步 判断用户是否存在 */
        const isUserExistbutton = () => {
            proxy.$refs.forgetFormRef1.validate((valid) => {
                if (valid) {
                    const requestData = {
                        account: data.form.account,
                        email: data.form.email,
                    }
                    isUserExist(requestData).then(response => {
                        const resData = response.data
                        console.log(resData.code)
                        if (resData.code === 200) {
                            proxy.$message({
                                message: resData.message,
                                type: "success"
                            })
                            if (active.value++ > 3) active.value = 0 //跳到下一步
                        }
                        /*
                        // 用户名不存在
                        else if (resData.code === 1024) {
                            proxy.$message.error(resData.message);
                            proxy.$refs.forgetFormRef1.resetFields();
                            return false;
                        }
                        // 邮箱不存在
                        else if (resData.code === 1025) {
                            proxy.$message.error(resData.message);
                            proxy.$refs.forgetFormRef1.resetFields();
                            return false;
                        }
                        */
                        else {
                            proxy.$message({
                                message: resData.message,
                                type: "error"
                            })
                            proxy.$refs.forgetFormRef1.resetFields();
                            return false
                        }
                    }).catch(error => {
                        data.submit_button_loading = false;
                        resetForm();
                    })


                } else {
                    console.log('error validate!!')
                    return false
                }
            })

        }

        /** 2.第二步 验证密码格式正确 */
        const passwordValidate = () => {
            proxy.$refs.forgetFormRef2.validate((valid) => {
                if (valid) {
                    if (active.value++ > 3) active.value = 0
                }
                else {
                    console.log('error validate!!')
                    return false
                }
            })
        }

        /** 3. 输入验证码 确定 */
        const resetPassword = () => {
            proxy.$refs.forgetFormRef3.validate((valid) => {
                if (valid) {
                    forget()
                    resetForm();
                    
                } else {
                    console.log('error submit!!')
                    resetForm();
                    return false
                }
            })
        }
        /** 忘记密码 */
        const forget = () => {
            const requestData = {
                account: data.form.account,
                email: data.form.email,
                password: data.form.password,
                verificationCode: data.form.code,
            }
            console.log(requestData)
            data.submit_button_loading = true;
            ForgetPassword(requestData).then(response => {
                const resData = response.data
                console.log(resData.code)
                if (resData.code === 200) {
                    proxy.$message({
                        message: resData.message,
                        type: "success"
                    })
                    active.value++
                } else {
                    proxy.$message({
                        message: resData.message,
                        type: "error"
                    })
                }
            }).catch(error => {
                data.submit_button_loading = false;
            })
        }
        return {
            active,
            // forgetFormRef,
            data,
            beforeSteps,
            resetPassword,
            handlerGetCode,
            isUserExistbutton,
            passwordValidate,

        }
    }
}
</script>

<style scoped>
.container {
    width: 100%;
    height: 100%;
    background-color: skyblue;
    position: fixed;
}

.page-container {
    width: 100%;
    height: 100vh;
    overflow-y: auto;
    background-size: cover;
    display: flex;
    align-items: center;
    justify-content: center;

    .forgot-password {
        width: 70%;
        height: 70vh;
        background: #FFFFFF;
        border-radius: 6px;
        .content {
            margin-top:50px;
            margin-right:30px;
            box-sizing: border-box;
        }

    }
}

.form-container {
    display: flex;
    align-items: center;
    justify-content: center;
}

.demo-ruleForm {
    margin-top: 60px;
    width: 400px;
}

.return-page-wr {
    float: left;
    font-size: 16px;
    margin-top: 10px;
    margin-bottom: 40px;
}

.reset-success {
    margin-top: 40px;

}
</style>